#include <jni.h>
#include <string>

#include <fcntl.h>
#include <sys/mman.h>

#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

extern "C" JNIEXPORT jstring JNICALL
Java_com_baize_myjniapplication_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from CCCC++";
    return env->NewStringUTF(hello.c_str());
}

extern "C"
JNIEXPORT jboolean JNICALL
Java_com_baize_myjniapplication_MainActivity_startMemoryMapping(JNIEnv *env, jobject thiz,
                                                                jstring mmap_id) {
    int fd;
    void *start;
    struct stat sb;
    fd = open("/etc/passwd", O_RDONLY); /* 打开/etc/passwd */
    fstat(fd, &sb); /* 取得文件大小 */
    start = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
    if (start == MAP_FAILED) /* 判断是否映射成功 */
        return false;
    printf("%s", start);
    munmap(start, sb.st_size);/* 解除映射 */
    close(fd);
    return true;
}

//void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offsize);
extern "C"
JNIEXPORT void JNICALL
Java_com_baize_myjniapplication_MainActivity_write(JNIEnv *env, jobject thiz) {
    std::string file = "/storage/emulated/0/baize.txt";
    // 可读可写｜创建
    // 得到文件句柄
    int fd = open(file.c_str(), O_RDWR | O_CREAT, S_IRWXU);
    // 创建文件大小
    int32_t size = getpagesize();

    //改变文件大小
    ftruncate(fd, size);

    // 建立映射
    //    malloc(1024);//主动调用 分配地址

    auto *m_ptr = static_cast<int8_t *>(
            mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)
    );

    //文件映射到内存
    std::string data = "人生得意须尽欢";
    memcpy(m_ptr, data.data(), data.size());

    close(fd);
}

extern "C"
JNIEXPORT jstring JNICALL
Java_com_baize_myjniapplication_MainActivity_read(JNIEnv *env, jobject thiz) {
    std::string file = "/storage/emulated/0/baize.txt";
    int fd = open(file.c_str(), O_RDWR | O_CREAT, S_IRWXU);
}